﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using ZhouYu.NewWorld.BLL.IService;
using ZhouYu.NewWorld.Model;
using ZhouYu.NewWorld.ViewModel;
using ZhouYu.NewWorld.Web.Models;

namespace ZhouYu.NewWorld.Web.Controllers
{
    public class CategoryController : Controller
    {
        //注入
        private ICategoryService _categoryService;

        public CategoryController(ICategoryService categoryService) 
        {
            _categoryService = categoryService;
        }

        //显示
        public JsonResult QueryCategory(int page, int limit, string categoryName)
        {
            ResponseResult resul = new ResponseResult();

            resul.code = 0;
            resul.msg = string.Empty;
            int count = 0;
            Expression<Func<Category, bool>> wherelambda = c => true;
            //模糊查询
            if (!string.IsNullOrEmpty(categoryName))
            {
                wherelambda = a => a.CategoryName.Contains(categoryName);
            }
            Expression<Func<Category, int>> orderlambda = c => c.CategoryId;
            resul.data = _categoryService.QueryPageList(page, limit, wherelambda, orderlambda, out count);
            resul.count = count;
            return Json(resul, JsonRequestBehavior.AllowGet);
        }

        //添加 
        public JsonResult AddCategory(Category category)
        {
            ResponseResult resul = new ResponseResult();
            category.UpdateTime = DateTime.Now;
            resul.Success = _categoryService.Add(category);
            return Json(resul);
        }

        //编辑
        public JsonResult UpdateCategory(Category category)
        {
            ResponseResult resul = new ResponseResult();
            category.UpdateTime = DateTime.Now;
            resul.Success = _categoryService.Update(category);
            return Json(resul);
        }

        //删除
        public JsonResult DeleteCategory(int id)
        {
            ResponseResult resul = new ResponseResult();
            resul.Success = _categoryService.BatchDeleteById(id);
            return Json(resul);
        }

        //批量删除
        public JsonResult BatchDelete(string Id)
        {
            //string转换string[]数据
            string[] strArray = Id.Split(',');
            int[] iNums;
            //string[]转换int[]
            iNums = Array.ConvertAll(strArray, int.Parse);
            ResponseResult resul = new ResponseResult();
            resul.Success = _categoryService.BatchDeleteById(iNums);
            return Json(resul);
        }
    }
}